Redux-saga中间件
Redux-saga和Redux-thunk一样,都是异步处理的中间件。
安装
1 | cnpm install redux-saga |
使用saga
1 | import { createStore, applyMiddleware, compose } from 'redux' |
定义异步发起action
容器组件TodoList中1
2
3
4componentDidMount(){
const action = getInitListData()
store.dispatch(action)
}
actionCreator中1
2
3export const getInitListData = () => ({
type: GTE_INIT_LIST_DATA, // GTE_INIT_LIST_DATA在reducer中不存在
})
actionTypes中1
export const GTE_INIT_LIST_DATA = 'get_init_list_data'
saga处理
1 | import { put, takeEvery } from 'redux-saga/effects' |
actionCreator中1
2
3
4export const initListDataAction = (value) => ({
type: INIT_LIST_DATA,
value
})
actionTypes中1
export const INIT_LIST_DATA = 'init_list_data'
reducer中1
2
3
4
5if (action.type === INIT_LIST_DATA){
const newState = JSON.parse(JSON.stringify(state));
newState.list = action.value
return newState;
}
https://github.com/rexyan/simple_react/tree/Redux-saga%E4%B8%AD%E9%97%B4%E4%BB%B6